package com.tianheng.modbus.socket;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/8/1 0001
 * since:      1.0.0.1
 * description:
 *
 **************************************************/

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;


/**
 * 客户端
 */
public class Client {
    public static void main(String args[]) throws Exception {
        CRC c = new CRC();
        // 要连接的服务端IP地址和端口
        String host = "127.0.0.1";
        int port = 55533;
        // 与服务端建立连接
        Socket socket = new Socket(host, port);
        // 建立连接后获得输出流
        OutputStream outputStream = socket.getOutputStream();

        byte[] b = new byte[] { 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x02 };
        byte[] bb = new byte[16]; //组合校验位后的数组
        byte[] check_digit = c.getCRC(b).getBytes();
        //把原始数据和校验位组合到bb数组中
        System.arraycopy(b, 0, bb, 0, b.length);
        for (int i = 0; i < check_digit.length; i++) {
            bb[12+i]=check_digit[i];
        }
        //写入请求数据
        socket.getOutputStream().write(bb);


        //获取服务端返回数据
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        for (int i = 0; i < len; i++) {
            System.out.print(bytes[i]);
        }
        System.out.println();

        //截取校验位之前的数据
        byte[] a = new byte[14];  //截取校验位之前的
        for (int i = 0; i < a.length; i++) {
            a[i] = bytes[i];
        }
        //截取校验位
        byte[] check1 = new byte[4];
        for (int i = 0; i < check1.length; i++) {
            check1[i]=bytes[14+i];
        }

        //计算校验码
        byte[] check2 = c.getCRC(a).getBytes();

        //如果传过来的校验位和计算得到的校验位相等，则计算并显示数据
        if(Arrays.equals(check2, check1)){
            int temperature = a[7]*10+a[9];
            double humidity = (a[11]*10+a[13]);
            System.out.println("温度："+temperature+"度"+"\n湿度:"+humidity+"%");
        }
        outputStream.close();
        inputStream.close();
        socket.close();
    }

    /**
     * byte数组转hex
     * @param bytes
     * @return
     */
    public static String byteToHex(byte bytes){
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        strHex = Integer.toHexString(bytes & 0xFF);
        /*for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }*/
        sb.append((strHex.length() == 1) ? "0" + strHex : strHex);
        return sb.toString().trim();
    }
}
